package com.appleframework.core;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * <一句话功能简述>
 * 帮助类,日期格式化等
 * <功能详细描述>
 * 
 * @author  apple.li
 * @version  [版本号, 2012-4-26]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class Helper
{ /**
     * 对指定当前时间添加“monthNum”个月后所得时间。
     * 
     * 
     * 
     * @param monthNum
     * @return
     */
    public static Date addMonth(int monthNum)
    {
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.MONTH, monthNum);
        return cal.getTime();
    }

    /**
     * 获取当日开始时间（时分秒都为0）。
     * @return
     */
    public static Date getBeginDay()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR, -12);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取当日结束时间
     * @return
     */
    public static Date getEndDay()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR, 11);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取当日结束时间
     * @return
     */
    public static Date getEndDate(Date date)
    {
        date.setHours(23);
        date.setMinutes(59);
        date.setSeconds(59);
        return date;
    }

    /**
     * 获取当年开始时间（时分秒都为0）。
     * @return
     */
    public static Date getBeginYear()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR, -12);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取当年结束时间
     * @return
     */
    public static Date getEndYear()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, 11);
        cal.set(Calendar.DAY_OF_MONTH, 31);
        cal.set(Calendar.HOUR, 11);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 对指定当前时间添加“dayNum”天后所得时间。
     * 
     * 
     * 
     * 
     * @param dayNum
     * @return
     */
    public static Date addDay(int dayNum)
    {
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.DATE, dayNum);
        return cal.getTime();
    }

    public static int getPercent(BigDecimal num, Integer totalnum)
    {
        if (num.intValue() == 0 || totalnum == 0)
        {
            return 0;
        }
        else
        {
            Double percent = num.doubleValue() / totalnum.doubleValue() * 100;
            return percent.intValue();
        }
    }

    /**
     * 获取当前时间。
     * 
     * 
     * 
     * @param monthNum
     * @return
     */
    public static Date getCurrentTime()
    {
        return new Date();
    }

    /**
     * 对指定时间添加“monthNum”个月后所得时间。
     * 
     * @param specDate Date
     * @param monthNum int
     * @return Date
     */
    public static Date addMonth(Date specDate, int monthNum)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(specDate);

        cal.add(Calendar.MONTH, monthNum);
        return cal.getTime();
    }

    /**
     * 获取月初时间。
     * 
     * @return Date
     */
    public static Date getMonthBegin()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);
        cal.set(Calendar.HOUR, -12);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取月末时间。
     * 
     * @return Date
     */
    public static Date getMonthEnd()
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 31);
        cal.set(Calendar.HOUR, 11);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 格式化日期
     * 
     * 
     * @param Date date 可以传null,传null时将返回当前时间格式化后的结果
     * 
     * 
     * 
     * @param String pattern
     * @return String
     */
    public static String formatDate(Date date, String pattern)
    {
        Date idate = date == null ? new Date() : date;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(idate);
    }

    /**
     * 格式化日期
     * 
     * 
     * 
     * @param Date date 可以传null,传null时将返回当前时间格式化后的结果
     * 
     * 
     * 
     * @return String
     */
    public static String formatDate(Date date)
    {
        Date idate = date == null ? new Date() : date;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(idate);
    }

    /**
     * 格式化日期
     * 
     * 
     * 
     * @param Date date 可以传null,传null时将返回空结果
     * 
     * 
     * 
     * @return String
     */
    public static String formatDates(Date date, String pattern)
    {
        if (date == null)
        {
            return "";
        }
        else
        {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(date);
        }
    }

    /**
     * 字符转换整型对象。
     * 
     * 
     * 
     * 空值及“”或者转换异常都转换为值为0的整型对象。
     * 
     * 
     * 
     */
    public static Integer strToInteger(String str)
    {
        Integer value = null;
        try
        {
            value = new Integer(str);
        }
        catch (Exception e)
        {
            value = Integer.valueOf(0);
        }

        return value;
    }

    /**
     * @param source:要替换的源字符串
     * @param parameters <key,要替换的值> 根据输入的内容，将资源文件中${}的变量予以替换
     * 
     * */
    public static String getPropertiesFile(String source, Map paramers)
    {
        if (source == null || "".equals(source.trim()))
        {
            return "";
        }
        String reg = "\\$\\{([\\w\\d]*)}";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(source);

        StringBuffer sbr = new StringBuffer();

        while (matcher.find())
        {
            Object val = "";
            val = paramers.get(matcher.group(1));
            val = val == null ? "" : val;
            matcher.appendReplacement(sbr, val.toString());
        }
        matcher.appendTail(sbr);

        return sbr.toString();
    }
    /**
     * 根据当前用户选择的语言,得到图片或模版的路径
     */
    public static String getDisplayPath(Locale locale)
    {
        String returnValue = "zh_cn";// 默认为中文 if (locale != null)
        {
            returnValue = locale.toString();
        }
        return returnValue.toLowerCase();
    }

    protected static String messageKey(Locale locale, String key)
    {
        return (localeKey(locale) + "." + key);
    }

    protected static String localeKey(Locale locale)
    {
        return (locale == null) ? "" : locale.toString();
    }

    protected static String escape(String string)
    {

        if ((string == null) || (string.indexOf('\'') < 0))
        {
            return string;
        }

        int n = string.length();
        StringBuffer sb = new StringBuffer(n);

        for (int i = 0; i < n; i++)
        {
            char ch = string.charAt(i);

            if (ch == '\'')
            {
                sb.append('\'');
            }

            sb.append(ch);
        }

        return sb.toString();

    }

    /**
     * <根据语言类型获取语言内容>
     * @param key
     * @param bundle
     * @param locale
     * @return [对应的值]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String getKeyByLanguage(String key, String bundle, Locale locale)
    {
        String returnValue = "";
        if (locale != null)
        {
            try
            {
                ResourceBundle myResources = ResourceBundle.getBundle(bundle, locale);
                returnValue = myResources.getString(key);
            }
            catch (MissingResourceException e)
            {
                return returnValue;
            }
        }
        return returnValue;
    }

    /**
     * 根据语言字串获取locale信息,默认返回中文locale
     * @param lang
     * @return
     */
    public static Locale getLocaleByLanguage(String lang)
    {
        try
        {
            String[] codes = lang.split("_");
            return new Locale(codes[0], codes[1]);
        }
        catch (Exception e)
        {
            return new Locale("zh", "CN");
        }
    }

    /**
     * 根据年月日获取企业图片存放路径
     * 
     * @return
     */
    public static String getImgPath()
    {
        Calendar lendar = Calendar.getInstance();
        return lendar.get(Calendar.YEAR) + "/" + (lendar.get(Calendar.MONTH) + 1) + "/"
                + lendar.get(Calendar.DAY_OF_MONTH);
    }


    public static String getBonusFormat(Double bonusNum)
    {
        String formatStr = "";
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyLocalizedPattern("￥#,#00");
        formatStr = df.format(bonusNum);
        return formatStr;
    }
    private static final String wan = "万";

    /**
     * <10000返回1万>
     * @param d
     */
    public static String getNumZH_CN(double d)
    {
        int i = (int) (d / 10000);
        if (i > 0)
        {
            return i + wan;
        }
        else
        {
            return "0" + wan;
        }
    }

    /**
     * 获取字符串长度，中文字符算2. <功能详细描述>
     * @param str
     * @return [参数说明]
     * 
     * @return int [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static int getStrLen(String str)
    {
        int count = 0;
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        while (m.find())
            count++;
        return str.length() + count;
    }

}
